const Post = require("../models/post");
const { Op } = require("sequelize");
const User = require("../models/user");
const commentService = require("../services/commentService");
const likeService = require("../services/likeService");
const messageService = require("../services/message");
const scoreService = require("../services/scoreService");

//判断日期是否需要加0
function addZero(num) {
  return num < 10 ? "0" + num : num;
}

// 新增文章
exports.add = async function (content, imgs, userId, place) {
  let todayDate = new Date();
  todayDate =
    todayDate.getFullYear() +
    "-" +
    addZero(todayDate.getMonth() + 1) +
    "-" +
    addZero(todayDate.getDate());
  const posts = await Post.findAll({
    where: {
      userId,
      createdAt: {
        [Op.gte]: new Date(todayDate),
      },
    },
  });
  if (posts.length >= 10) {
    throw new Error("一天最多只可发表10次动态");
  }
  imgs = JSON.stringify(imgs);
  await Post.create({
    content,
    imgs,
    userId,
    place,
  });
  //创建动态积分加2分
  await scoreService.add(userId,2,'发表动态')
};

//获取文章列表
exports.getPostList = async function (college, size, page, userId) {
  size = parseInt(size);
  page = parseInt(page);
  let rows, count;
  let data;
  data = await Post.findAndCountAll({
    attributes: ["id", "imgs", "content"],
    // where: {
    //   place: {
    //     [Op.substring]: college,
    //   },
    // },
    include: {
      model: User,
      attributes: ["id", "username", "avatar", "createdAt"],
      as: "user",
    },
    order: [["createdAt", "DESC"]],
    limit: size,
    offset: (page - 1) * size,
  });
  if (userId) {
    const likeArr = await likeService.userLikePost(userId);
    if (likeArr.length > 0) {
      data.rows.forEach((item) => {
        if (likeArr.indexOf(item.id) > -1) {
          item.dataValues.likeStatus = true;
        } else {
          item.dataValues.likeStatus = false;
        }
      });
    } else {
      data.rows.forEach((item) => {
        item.dataValues.likeStatus = false;
      });
    }
  }

  rows = data.rows;
  count = data.count;

  rows.forEach((item) => {
    item.imgs = JSON.parse(item.imgs);
  });

  return {
    rows,
    count,
  };
};

//获取一条文章
exports.getOnePost = async function (postId, userId) {
  let post = await Post.findOne({
    attributes: [
      "id",
      "imgs",
      "content",
      "place",
      "likeNum",
      "commentNum",
      "createdAt",
    ],
    where: {
      id: postId,
    },
    include: {
      model: User,
      attributes: ["id", "username", "avatar"],
      as: "user",
    },
  });

  if (post === null) {
    throw new Error("文章不存在，可能已被删除");
  }

  if (userId) {
    post.dataValues.likeStatus = await likeService.isLikePost(userId, postId);
    // post.dataValues.isConcern = await fansService.isConcern(userId,post.user.id);
  }

  post.dataValues.imgs = JSON.parse(post.dataValues.imgs);

  return post;
};

//删除文章
exports.delete = async function (postId, userId) {
  //删除文章
  await Post.destroy({
    where: { id: postId },
  });

  //删除该文章下的所有评论
  await commentService.deleteAll(postId);

  //删除该文章下的所有点赞
  await likeService.deleteAll(postId);

  //删除该文章下的所有消息
  await messageService.deleteAll(postId);

  // 积分减2
  await scoreService.add(userId, -1, "删除动态");
};

//获取某个人所有动态文章信息
exports.getAllDynamic = async function (userId, size, page) {
  size = parseInt(size);
  page = parseInt(page);
  let { rows, count } = await Post.findAndCountAll({
    where: {
      userId,
    },
    attributes: [
      "id",
      "imgs",
      "content",
      "place",
      "likeNum",
      "commentNum",
      "createdAt",
    ],
    order: [["createdAt", "DESC"]],
    limit: size,
    offset: (page - 1) * size,
    include: {
      model: User,
      attributes: ["id", "username", "avatar"],
      as: "user",
    },
  });

  console.log(rows);
  rows.forEach((item) => {
    item.imgs = JSON.parse(item.imgs);
  });

  const dynamicArr = rows;
  return {
    dynamicArr,
    dynamicCount: count,
  };
};
